package com.heriparid.fragmentinjection.ui.fragments;

import static butterknife.Views.*;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.InjectView;

import com.heriparid.fragmentinjection.R;
import com.heriparid.fragmentinjection.controllers.MainController;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ItemListFragment extends Fragment implements OnItemClickListener {

	@InjectView(R.id.fragment_item_list_listview)
	ListView mListView;
	@Inject
	MainController mController;
	
	private static final String TAG = ItemListFragment.class.getSimpleName();
	
	private boolean mInitialCreate;
	private ArrayAdapter<String> mAdapter;
	private static final List<String> values = new ArrayList<String>();
	
	// Dummy data
	static {
		values.add("Satu");
		values.add("Dua");
		values.add("Tiga");
		values.add("Empat");
		values.add("Lima");
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.v(TAG, "onCreate: savedInstanceState " + (savedInstanceState == null ? "==" : "!=") + " null");
		
		// Restore state
		if(savedInstanceState != null){
			mInitialCreate = false;
		}
		// Otherwise, default state
		else{
			mInitialCreate = true;
		}
		
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		
		View view = inflater.inflate(R.layout.item_list_layout_fragment, container, false);
		inject(this, view);
		
		mListView.setOnItemClickListener(this);
		
		mAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_row_items, R.id.tv_item, values);
	
		// set adapter
		mListView.setAdapter(mAdapter);
		
		if(mInitialCreate){
			mInitialCreate = false;
		}
		
		return view;
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		reset(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// Highlight the selected row
		mListView.setItemChecked(position, true);
		
		// Notify controller		
		mController.onItemClicked(position);
	}
	
	public static ItemListFragment newInstance(){
		ItemListFragment fragment = new ItemListFragment();
		return fragment;
	}
}
